package com.sinothk.fc.collect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.fc.collect.entity.CollectEntity;
import com.sinothk.fc.collect.mapper.CollectMapper;
import com.sinothk.fc.collect.service.ICollectService;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;

/**
 * @Description: 商品收藏
 * @Author: Liangyt
 * @Date: 2022-10-05
 * @Version: V1.0
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, CollectEntity> implements ICollectService {

    @Override
    public boolean addOrCancelCollect(String storeId, String goodsId) throws Exception {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");

        LambdaQueryWrapper<CollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectEntity::getStoreId, storeId);
        wrapper.eq(CollectEntity::getGoodsId, goodsId);
        wrapper.eq(CollectEntity::getCustomerId, loginUser.getId());
        CollectEntity collect = this.getOne(wrapper);

        if (collect == null) {
            CollectEntity collectReq = new CollectEntity();
            collectReq.setStoreId(storeId);
            collectReq.setGoodsId(goodsId);
            collectReq.setCustomerId(loginUser.getId());
            this.save(collectReq);
            return true;
        }else{
            this.remove(wrapper);
            return false;
        }
    }

    @Override
    public CollectEntity getCurrCollectStateByStoreId(String storeId) throws Exception {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");

        LambdaQueryWrapper<CollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectEntity::getStoreId, storeId);
        wrapper.eq(CollectEntity::getGoodsId, "");
        wrapper.eq(CollectEntity::getCustomerId, loginUser.getId());

        return this.getOne(wrapper);
    }

    @Override
    public CollectEntity getCurrCollectStateByGoodsId(String storeId, String goodsId) throws Exception {

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");

        LambdaQueryWrapper<CollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectEntity::getStoreId, storeId);
        wrapper.eq(CollectEntity::getGoodsId, goodsId);
        wrapper.eq(CollectEntity::getCustomerId, loginUser.getId());

        return this.getOne(wrapper);
    }
}
